#pragma once

#include <iostream>
#include <pthread.h>
#include <string>
#include <cstdio>
#include <cstring>
#include <functional>

namespace ThreadModule
{
    static int num = 1;
    class Thread
    {

    using func_t =std::function<void()>;
    public:
        Thread(func_t func)
            : _tid(0)
             ,_isdetach(false)
            ,_isrunning(false)
            ,_res(nullptr)
            , _func(func)
        {
            _name = "thread-" + std::to_string(num++);
        }

        void Detach()
        {
            if (_isdetach)
            {
                return;
            }
            if (_isrunning)
            {
                pthread_detach(_tid);
                std::cout<<_name<<" detach success"<<std::endl;
            }
            EnableDetach();
        }

        bool Start()
        {
            if(_isrunning)
            {
                return false;
            }

            int n = pthread_create(&_tid, nullptr, Routine, this);
            if (n != 0)
            {
                std::cerr << "create thread failed" << std::endl;
                return false;
            }
            else 
            {
                std::cout<< "create thread success" << std::endl;
                return true;
            }
        }

        bool Stop()
        {
            if (_isrunning)
            {
                int n = pthread_cancel(_tid);
                if (n != 0)
                {
                    std::cerr << "cancel thread failed" << std::endl;
                    return false;
                }
                else
                {
                    _isrunning = false;
                    std::cout<<_name<<" stop success"<<std::endl;
                    return true;
                }
            }
            return false;
        }

        void Join()
        {
            if (_isdetach)
            {
                std::cout<<"线程已被分离,join无效"<<std::endl;
                return;
            }
            int n = pthread_join(_tid, &_res);
            if (n != 0)
            {
                std::cerr << "join thread failed" << std::endl;
            }
            else
            {
                std::cout<< "join thread success" << std::endl;
            }
        }

        ~Thread() {}

    private:
        pthread_t _tid;
        std::string _name;
        bool _isdetach;
        bool _isrunning;
        void *_res;
        func_t _func;

        void EnableDetach()
        {
            _isdetach = true;
        }

          void EnableRunning()
        {
            _isrunning = true;
        }

        static void* Routine(void* arg)
        {
            Thread* self=static_cast<Thread*>(arg);
            self->EnableRunning();

            if (self->_isdetach)
            {
                self->Detach();
            }

            pthread_setname_np(self->_tid,self->_name.c_str());
            self->_func();

            return nullptr;

        }
    };
}